/**
 * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.jfinal.weixin.controller;

import com.jfinal.log.Log;
import com.jfinal.weixin.demo.HbThread;
import com.jfinal.weixin.demo.PostThread;
import com.jfinal.weixin.model.Score;
import com.jfinal.weixin.model.User;
import com.jfinal.weixin.model.WeixinInfo;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.*;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.*;
import com.jfinal.weixin.sdk.utils.ImgMarkUtil;
import com.jfinal.weixin.sdk.utils.StringUtil;

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由，
 * 并设置好weixin开发者中心的 URL 与 token ，使 URL 指向该
 * DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
public class WeixinMsgController extends MsgControllerAdapter {

    static Log logger = Log.getLog(WeixinMsgController.class);
    private static final String helpStr = "呵呵";

    public ApiConfig getApiConfig() {
        ApiConfig ac = new ApiConfig(WeixinInfo.dao.getWeixinInfoById(1));
        return ac;
    }

    public String signed(String openid) {
        User user = User.dao.getUserByOpenid(openid);
        Boolean flag = Score.dao.isAddedToday(user.getInt("id"));
        String result;
        if (!flag) {
            Score.dao.addScore(openid);
            int score = user.getInt("score");
            result = "签到成功!您已经签到" + (score+1) + "次,每签到10次送红包哦!";
        } else {
            result = "请明天再来签到";
        }
        return result;
    }

    protected void processInTextMsg(InTextMsg inTextMsg) {
        String content = inTextMsg.getContent();
        String result;
        String openid = inTextMsg.getFromUserName();
        boolean issend = true;
        OutNewsMsg outTextMsg = new OutNewsMsg(inTextMsg);
        logger.debug(openid + "发送消息来了:" + content);
        if (content.equals("签到")) {
            result = signed(openid);
            outTextMsg.addNews(result, StringUtil.BKMDESC, StringUtil.BKMIMG, StringUtil.HBSM);
        } else if (content.contains("朋友圈")) {
            outTextMsg.addNews("红安人专用装逼朋友圈", StringUtil.BKMTITLE, "", "http://www.0713jc.com/zb?openid=" + openid);
        }  else if (content.contains("修改订阅状态")) {
            if (User.dao.updateDingyue(openid) == 0) {
                outTextMsg.addNews("订阅成功,每日将会推送订阅天气哦", StringUtil.BKMTITLE, "", "http://www.0713jc.com/zb?openid=" + openid);
            } else {
                outTextMsg.addNews("取消订阅成功,本月不再推送天气", StringUtil.BKMTITLE, "", "http://www.0713jc.com/zb?openid=" + openid);
            }
        } else if (content.equals("结婚证")) {
            outTextMsg.addNews("还要带上你的姓名啊锅锅。", StringUtil.BKMTITLE, "", "http://www.0713jc.com/admin");
        } else if (content.equals("模板446705260")) {
            outTextMsg.addNews("成功", StringUtil.BKMDESC, StringUtil.BKMIMG, StringUtil.BKMURL);
            PostThread indexThread = new PostThread();
            indexThread.start();
        }else if (content.equals("红包446705260")) {
            outTextMsg.addNews("成功", StringUtil.BKMDESC, StringUtil.BKMIMG, StringUtil.BKMURL);
            HbThread indexThread = new HbThread();
            indexThread.start();
        } else if (content.contains("红包")) {
            outTextMsg.addNews("不定期发送红包,签到10次必送", StringUtil.HBDESC,StringUtil.BKMIMG , StringUtil.HBSM);
        } else if (StringUtil.isjiehun(content)) {
            String name = content.substring(3);
            ImgMarkUtil.mark(getRequest().getServletContext().getRealPath("/") + "/jiehun/yuan2.jpg", getRequest().getServletContext().getRealPath("/") + "jiehun/" + openid + ".jpg", name);
            outTextMsg.addNews("结婚证生成成功,请点击获取", StringUtil.BKMDESC, "http://www.0713jc.com/jiehun/" + openid + ".jpg", "http://www.0713jc.com/zb/jiehun?openid=" + openid);
        } else if (StringUtil.ismb(content)) {
//            String name = content.substring(2);
//            int babyid = StringUtil.getInteger2(name);
//            VoteController voteController =new VoteController();
           // String voteresult = voteController.dovote(babyid,openid);
            String voteresult="投票结束";
            System.out.print("投票结果:"+voteresult);
            outTextMsg.addNews(voteresult, "持续签到,不定期送微信红包",StringUtil.BKMIMG, "http://www.0713jc.com/admin");
        } else if(StringUtil.is2016(content)){
            String name = content.substring(4);
            int voteid = StringUtil.getInteger2(name);
            String voteresult = new VoteController().revote(openid,voteid);
            outTextMsg.addNews(voteresult, "红安红和红安人都可以投票哦","", "http://www.0713jc.com/admin");
        }else if (content.contains("萌宝") || content.contains("投票")) {
            outTextMsg.addNews("庆六一！晒萌宝！赢大奖！点击这里投票", "点击这里，立即报名！红安红萌宝大赛期待您的参与！投票期还没到，请提前做好准备哦！",
                    "https://mmbiz.qlogo.cn/mmbiz/5O803obudySDAZgfBbOjQ4equiaQOCnRqRY4hcSZKgYnWovu7qgXWCJGzhziaeVIH7JjAvTyaib6YV2mSeN5giavVQ/0?wx_fmt=jpeg",
                    "http://www.0713jc.com/vote");
            outTextMsg.addNews("点击这里报名", "点击这里，立即报名！红安红萌宝大赛期待您的参与！投票期还没到，请提前做好准备哦！",
                    "https://mmbiz.qlogo.cn/mmbiz/5O803obudyRmOVeOhJTia4uE2jo3ic6o8byjjN9ZcfDm9icMIfUv16XnePDfyhhovCHibynOcbKgIhHs6BNJZ1c8vg/0?wx_fmt=jpeg",
                    "http://form.mikecrm.com/RfX9KC");
        } else {
            outTextMsg = TulingApi.getTulingResult(User.dao.getUserByOpenid(openid).getInt("id"), content, inTextMsg);
        }

        render(outTextMsg);
    }

    /**
     * 实现父类抽方法，处理自定义菜单事件
     */
    protected void processInMenuEvent(InMenuEvent inMenuEvent) {
        String key = inMenuEvent.getEventKey();
        String result;
        String openid = inMenuEvent.getFromUserName();
        User user = User.dao.getUserByOpenid(openid);
        logger.debug(openid + "点击了菜单:" + key);
        OutNewsMsg outMsg = new OutNewsMsg(inMenuEvent);
        if (key.equals("HAQD")) {
            result = signed(openid);
            outMsg.addNews(result, StringUtil.HBDESC, StringUtil.BKMIMG, StringUtil.HBSM);
        } else if (key.equals("HAXW")) {
            List<News> list = NewsApi.getNews();
            outMsg.addNews(StringUtil.BKMTITLE, StringUtil.BKMDESC, StringUtil.BKMIMG, StringUtil.BKMURL);
            outMsg.addNews(list);
        } else if (key.equals("HAJQ")) {
            outMsg = TulingApi.getTulingResult(user.getInt("id"), "自我介绍", inMenuEvent);
        } else if (key.equals("HAPY")) {
            outMsg.addNews("红安人专用装逼朋友圈", StringUtil.BKMDESC, "", "http://www.0713jc.com/zb?openid=" + openid);
        }  else if (key.equals("HAJH")) {
            outMsg.addNews("回复结婚证+你的姓名,即可获得新鲜出炉的结婚证一张", "直接在对话框内回复结婚证+你的姓名,即可获得新鲜出炉的结婚证一张", "", "http://www.0713jc.com/zb?openid=" + openid);
        } else if (key.equals("HAMB")) {
            outMsg.addNews("庆六一！晒萌宝！赢大奖！点击这里投票", "点击这里，立即报名！红安红萌宝大赛期待您的参与！投票期还没到，请提前做好准备哦！",
                    "https://mmbiz.qlogo.cn/mmbiz/5O803obudySDAZgfBbOjQ4equiaQOCnRqRY4hcSZKgYnWovu7qgXWCJGzhziaeVIH7JjAvTyaib6YV2mSeN5giavVQ/0?wx_fmt=jpeg",
                    "http://www.0713jc.com/vote");
            outMsg.addNews("点击这里报名", "点击这里，立即报名！红安红萌宝大赛期待您的参与！投票期还没到，请提前做好准备哦！",
                    "https://mmbiz.qlogo.cn/mmbiz/5O803obudyRmOVeOhJTia4uE2jo3ic6o8byjjN9ZcfDm9icMIfUv16XnePDfyhhovCHibynOcbKgIhHs6BNJZ1c8vg/0?wx_fmt=jpeg",
                    "http://form.mikecrm.com/RfX9KC");
        } else {
            outMsg.addNews(StringUtil.BKMTITLE, StringUtil.BKMDESC, StringUtil.BKMIMG, StringUtil.BKMURL);
        }
        render(outMsg);
    }


    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    protected void processInFollowEvent(InFollowEvent inFollowEvent) {
        if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent())) {
            String openid = inFollowEvent.getFromUserName();
            OutTextMsg outMsg = User.dao.setSubscribeMsgByOpenidAndEvent(openid, inFollowEvent);
            render(outMsg);
        }
        // 如果为取消关注事件，将无法接收到传回的信息
        if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent())) {
            String openid=inFollowEvent.getFromUserName();
            logger.debug("取消关注： " + openid);
            String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            java.sql.Timestamp ts_date = java.sql.Timestamp.valueOf(nowTime);
            User user = User.dao.getUserByOpenid(openid).set("subscribe", 0).set("time", ts_date);
            user.update();
            renderOutTextMsg("I am looking forward to See you again.");
        }
    }

    @Override
    protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
        OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
        String openid = inQrCodeEvent.getFromUserName();
        if (InQrCodeEvent.EVENT_INQRCODE_SUBSCRIBE.equals(inQrCodeEvent.getEvent())) {
            outMsg = User.dao.setSubscribeMsgByOpenidAndEvent(openid, inQrCodeEvent);
            render(outMsg);
            //outMsg.setContent("感谢您的关注，二维码内容：" + inQrCodeEvent.getEventKey());

            //render(outMsg);
        }
        if (InQrCodeEvent.EVENT_INQRCODE_SCAN.equals(inQrCodeEvent.getEvent())) {

            User user = User.dao.getUserByOpenid(openid);
            int identy = user.getInt("id");
            outMsg.setContent("扫扫更健康.第" + identy + "位关注我们公众号的老朋友.敢不敢跟我说话,敢不敢陪我聊聊天?");
        }
    }

    @Override
    protected void processInLocationEvent(InLocationEvent inLocationEvent) {
//		logger.debug("发送地理位置事件：" + inLocationEvent.getFromUserName());
//        ApiResult apiResult = MapApi.getMapResult(inLocationEvent.getLatitude(),inLocationEvent.getLongitude());
//		OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
//        JSONObject jo = (JSONObject) JSONObject.parse(apiResult.toString());
//        String a = jo.getString("result").toString();
//        jo =  (JSONObject) JSONObject.parse(a);
//		outMsg.setContent("恩在"+jo.getString("address")+"搞摩斯.唰刀我听果黑");
//		render(outMsg);

        List<News> list = NewsApi.getNews();
        OutNewsMsg outNewsMsg = new OutNewsMsg(inLocationEvent);
        outNewsMsg.addNews(StringUtil.BKMTITLE, StringUtil.BKMDESC, StringUtil.BKMIMG, StringUtil.BKMURL);
        outNewsMsg.addNews(list);
        render(outNewsMsg);
    }

    @Override
    protected void processInMassEvent(InMassEvent inMassEvent) {

    }


    @Override
    protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
        logger.debug("语音识别事件：" + inSpeechRecognitionResults.getFromUserName());
        OutTextMsg outMsg = new OutTextMsg(inSpeechRecognitionResults);
        outMsg.setContent("你说的是:" + inSpeechRecognitionResults.getRecognition() + "但是我现在却木有能力回应你啊,亲");
        render(outMsg);
    }

    @Override
    protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent) {
        logger.debug("测试方法：processInTemplateMsgEvent()");
        renderNull();
    }

    @Override
    protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inVoiceMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInVideoMsg(InVideoMsg inVideoMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inVideoMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inShortVideoMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInLocationMsg(InLocationMsg inLocationMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inLocationMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInLinkMsg(InLinkMsg inLinkMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inLinkMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInCustomEvent(InCustomEvent inCustomEvent) {
        logger.debug("测试方法：processInCustomEvent()");
        renderNull();

    }

    @Override
    protected void processInImageMsg(InImageMsg inImageMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inImageMsg);
        render(outCustomMsg);
    }


}



